import javax.swing.*;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Vector;
import java.util.regex.Matcher;

public class Controller {
	ReaderFrame frame;
	Model model;
	Thread thread = null;// 添加目录线程 不占用主控制线程

	public Controller(Model model, ReaderFrame frame) {
		this.model = model;
		this.frame = frame;
	}

	/**
	 * 清空书签内容监听器
	 * @return
	 */
	ActionListener clearMarkListener() {
		return e -> {
			JOptionPane.showMessageDialog(frame, model.file.getName() + "的书签已清空!");
			model.book_mark_map.clear();
			model.logger.info(model.file.getName() + " mark list is clean.");
		};
	}

	/**
	 * 添加书签内容监听器
	 * @return
	 */
	ActionListener addMarkListener() {
		return e -> {
			frame.dialog_process = new MyDialog(frame, model, this).addMark();
			frame.dialog_process.setVisible(true);
		};
	}

	ActionListener manageMarkListener() {
		return e -> {
			Dialog dialog = new MyDialog(frame, model, this).listMark();
			dialog.setVisible(true);
		};
	}

	/**
	 * 更改阅读文件
	 * @param model 模型
	 * @return
	 */
	ActionListener changeFile(Model model) {// 更改文件后操作
		return e -> {
			saveMarkMap();
			Settings.apply();
			model.file = FileOperator.chooser(frame);
			model.book_mark_map = model.gson.fromJson(String.valueOf(model.book_map.get(model.file.getName())), HashMap.class);
			if (model.book_mark_map == null) {
				model.book_mark_map = new HashMap<>();
			}
			frame.w_panel.setVisible(false);
			displayFile(model);
		};
	}

	/**
	 * 更改颜色模式
	 * @param style_value 颜色模式枚举
	 * @return
	 */
	ActionListener colorStyleListener(ColorStyle style_value) {// 动作监听器 颜色模式改变
		return e -> {
			Color[] colors = ColorStyle.getStyleColors(style_value);
			frame.text_area.setBackground(colors[1]);
			frame.text_area.setForeground(colors[0]);
			frame.catalog_list.setBackground(colors[1]);
			frame.catalog_list.setForeground(colors[0]);
			Settings.setting_map.replace("color_style", style_value);
			model.logger.info("color style is change:" + style_value.name());
		};
	}

	ChangeListener catalogChangeListener() {// 按钮监听器 显示目录
		return ch -> {
			JToggleButton toggleButton = (JToggleButton) ch.getSource();
			if (toggleButton.isSelected()) {
				try {
					thread.start();
				} catch (IllegalThreadStateException ignored) {
					frame.catalog_list.setVisible(false);
					toggleButton.setEnabled(true);
				} catch (NullPointerException npe) {
					thread = new Thread(this::displayCatalog);
					thread.start();
				}
				frame.catalog_list.setVisible(true);
				frame.w_panel.setVisible(true);
			} else {
				frame.catalog_list.setVisible(false);
				frame.w_panel.setVisible(false);
			}
			frame.validate();
			frame.repaint();
			frame.text_area.getCaret().setVisible(true);
		};
	}

	/**
	 * 显示弹窗
	 */
	private void displayCatalog() {// 搜索目录
		frame.w_panel.setVisible(false);
		frame.dialog_process.setBounds(frame.getX(), frame.getY(), 200, 100);
		frame.dialog_process.setVisible(true);
		Matcher chapter_name_matcher = Model.matcher(model.file_text, model.regular_expression);
		model.catalog_map.clear();
		frame.catalog_list.removeAll();
		Vector<String> catalogs = new Vector<>();

		System.out.println(chapter_name_matcher.groupCount());
		while (chapter_name_matcher.find()) {
			model.catalog_map.put(chapter_name_matcher.group(), chapter_name_matcher.start() + 3);// 目录名与索引匹配，目录名：索引值
			catalogs.add(chapter_name_matcher.group());
		}

		frame.catalog_list.setListData(catalogs);
		frame.catalog_list.addListSelectionListener(e -> {
			frame.text_area.setCaretPosition(model.catalog_map.get(frame.catalog_list.getSelectedValue()));
			frame.text_area.getCaret().setVisible(true);
		});

		frame.dialog_process.dispose();
		frame.w_panel.setVisible(true);
		frame.validate();
		frame.repaint();
		System.gc();
	}

	void displayFile(Model model) {// 显示文本
		frame.catalog_visible_toggleButton.setEnabled(true);
		try {
			model.last_open = model.file.getAbsolutePath();
		} catch (NullPointerException ne) {
			new MyDialog(frame).warning("选择文件为空，请重新选择。").setVisible(true);
			return;
		}
		Settings.setting_map.replace("last_open", model.last_open);
		model.file_type = model.file.getName().substring(model.file.getName().lastIndexOf('.') + 1);
		if (model.file_type.equals("txt")) {// 判断文件类型 TXT文本
			try {
				model.file_text = FileOperator.readFile(model.file);
			} catch (FileNotFoundException NOF) {
				JOptionPane.showMessageDialog(null, "文件不存在！请检查", "错误", JOptionPane.ERROR_MESSAGE);
			}
			frame.text_area.setText(model.file_text);
			frame.catalog_visible_toggleButton.setEnabled(true);
		} else {
			JOptionPane.showMessageDialog(null, "不支持的文件！请重新选择", "警告", JOptionPane.WARNING_MESSAGE);
			frame.text_area.setText("读取错误，请重新选择！");
			frame.catalog_visible_toggleButton.setEnabled(false);
		}
		frame.file_path_label.setText(model.file.getPath());
		thread = new Thread(this::displayCatalog);
		if (frame.catalog_visible_toggleButton.isSelected())
			thread.start();
		frame.text_area.setText(model.file_text);
		frame.text_area.setCaretPosition(0);
		frame.catalog_visible_toggleButton.setEnabled(true);
		System.gc();
	}

	WindowListener windowListener() {
		return new WindowAdapter() {
			public void windowOpened(WindowEvent e) {// 窗口开启事件
				super.windowOpened(e);
				Color[] colors = ColorStyle.getStyleColors(model.color_style);
				frame.text_area.setBackground(colors[1]);
				frame.text_area.setForeground(colors[0]);
				frame.catalog_list.setBackground(colors[1]);
				frame.catalog_list.setForeground(colors[0]);
			}

			public void windowClosing(WindowEvent e) {// 窗口关闭事件
				super.windowClosing(e);
				if (!e.getWindow().equals(frame) || model.file == null) return;//如果不是主窗口
				saveMarkMap();
			}
		};
	}

	private void saveMarkMap() {
		System.out.println(model.file.getName());
		if (!model.book_map.containsKey(model.file.getName())) {
			model.book_map.put(model.file.getName(), model.book_mark_map);
		} else {
			model.book_map.replace(model.file.getName(), model.book_mark_map);
		}

		if (!model.book_map.isEmpty()) {// 如果总书签列表不为空
			if (!Settings.setting_map.containsKey("book_map")) {// 如果设置不含有此映射
				Settings.setting_map.put("book_map", model.book_map);
			} else {
				Settings.setting_map.replace("book_map", model.book_map);
			}
		}
	}

}
